package cn.iocoder.yudao.boot.common.validate;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.PhoneUtil;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;

@Target({
    ElementType.METHOD,
    ElementType.FIELD,
    ElementType.ANNOTATION_TYPE,
    ElementType.CONSTRUCTOR,
    ElementType.PARAMETER,
    ElementType.TYPE_USE
})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(
        validatedBy = TelAnno.TelephoneValidator.class
)
public @interface TelAnno {

    String message() default "电话格式不正确";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class TelephoneValidator implements ConstraintValidator<TelAnno, String> {

        @Override
        public void initialize(TelAnno annotation) {
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            // 如果手机号为空，默认不校验，即校验通过
            if (CharSequenceUtil.isEmpty(value)) {
                return true;
            }
            // 校验手机
            return PhoneUtil.isTel(value) || PhoneUtil.isPhone(value);
        }

    }
}
